<?php
/*
* Class teia\webdev\php\core\SettingItem
* Core class for web site settings
*
* @author Bernardo Quibiana
* @date created: 20111127
*
* @date modified: 20111127
* @modified: Bernardo Quibiana
*/

// namespace declaration: Abstract Data Types
namespace teia\webdev\php\core;

require_once 'MySqlLink.inc';

class SettingItem {
	private $context;
	private $object;
	private $field;
	private $value;

	public function __construct($context, $object, $field, $value) {
		$this->context = $context;
		$this->object = $object;
		$this->field = $field;
		$this->value = $value;
	}

	static function db_factory($conds=NULL, $limit=0, $db_tb='conf_settings') {
		$settings_items = array();
		$cols = array('context', 'object', 'field', 'value');
		
		try {
			// execute query
			$db_link = MySqlLink::link_factory();
			$result = $db_link->select($db_tb, $cols, $conds);
			// fetch results
			if ($result && is_resource($result)) {
				// fetch items
				while ($result_row = mysql_fetch_assoc($result)) {
					$it = self::db_synthesis($result_row);
					$it_context = $it->get('context');
					$settings_items['context'] = $it;
				}
			} else {
				throw new \Exception('SettingItem: Unable to load setting item from database', 200);
			}
		} catch (\Exception $e) {
			throw $e;
		}
		
		return $settings_items;
	}
	
	static function db_fetch($context, $object, $field, $db_tb='conf_settings') {
		$db_link = MySqlLink::link_factory();
		$cols = array('context', 'object', 'field', 'value');
		$conds = array('context' => $context, 'object' => $object, 'field' => $field);
		$result = $db_link->select($db_tb, $cols, $conds);
		
		if ($result && is_resource($result)) {
			$result_row = mysql_fetch_assoc($result);
			return self::db_synthesis($result_row);	
		} else {
			throw new \Exception('SettingItem: Unable to load setting item from database', 200);
		}
	}
	
	static function db_synthesis($tb_row) {
		$context = $tb_row['context'];
		$object = $tb_row['object'];
		$field = $tb_row['field'];
		$value = $tb_row['value'];
		$setting = new SettingItem($context, $object, $field, $value);
		
		return $setting;
	}

	public function get($property) {
		return isset($this->$property) ? $this->$property : null;
	}

	public function set($property, $value) {
		if (isset($this->$property)) {
			$this->$property = $value;
		}
	}

	public function to_array() {
		return array('context' => $this->context, 'object' => $this->object, 'field' => $this->field, 'value' => $this->value);
	}
}
?>